package com.jihox.abookpro;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.jihox.abookpro.R;
import com.jihox.abookpro.adapter.ResultFollowAdapter;
import com.jihox.abookpro.domain.ResultEntity;

public class OrderLogistic extends BaseActivity {
	private ListView lv;
	private ResultFollowAdapter adapter;
	private List<ResultEntity> rs = new ArrayList<ResultEntity>();
	private boolean sort_up = true;
	private int state = 0;

	public static final int STATE_RECEIVED = 3;
	public static final int STATE_ON_PASSAGE = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.order_logistic);
		initView();
		initHeader();
	}

	// init头部
	private void initHeader() {
		Button backBtn = (Button) findViewById(R.id.ivBack);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				OrderLogistic.this.finish();
			}
		});
		TextView center = (TextView) findViewById(R.id.tvTitle);
		center.setText(R.string.View_Logistic);
	}

	private void initView() {
		lv = (ListView) findViewById(R.id.followListView);
		lv.setAdapter(adapter);
		parse(getIntent().getExtras().getString("jsonStr"));
	}

	@SuppressWarnings("unchecked")
	public void parse(String jsonStr) {
		try {

			JSONObject obj = new JSONObject(jsonStr);
			if (obj.get("message").equals("ok")) {
				JSONArray data = obj.getJSONArray("data");

				if (data != null) {
					for (int i = 0; i < data.length(); i++) {
						JSONObject item = data.getJSONObject(i);
						ResultEntity entity = new ResultEntity();
						entity.setTime(item.getString("time"));
						entity.setContext(item.getString("context"));
						rs.add(entity);
					}
				}

				Collections.reverse(rs);
				state = Integer.parseInt(obj.get("state").toString());
				adapter = new ResultFollowAdapter(OrderLogistic.this, rs,
						sort_up, state);
				lv.setAdapter(adapter);

				if (state == STATE_RECEIVED) {
					findViewById(R.id.colorLine).setBackgroundResource(
							R.drawable.red_line_green);
					findViewById(R.id.dot_full).setVisibility(View.VISIBLE);
				}
				if (state == STATE_ON_PASSAGE) {
					findViewById(R.id.colorLine).setBackgroundResource(
							R.drawable.red_line_blue);
				}

			} else {
				showToast(obj.getString("message"));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onBackPressed() {
		// overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
		super.onBackPressed();
	}
}
